package com.recharge.common.util;

import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelUtil {

    /**
     * 导出列表到本地EXCEL
     * @param response 返回信息对象
     * @param downloadList 导出列表
     * @param fileTemplatePath 文件模板信息
     * @param downloadName 下载名称
     */
    public static boolean exportExcel (HttpServletResponse response, List<Object> downloadList, String fileTemplatePath, String downloadName) {
        Map<String,Object> map = new HashMap<>();
        map.put("data",downloadList);
        map.put("fun", new FunctionUtil());
        InputStream is = null;
        OutputStream os = null;
        try{
            is = new FileInputStream(fileTemplatePath);
            // 实例化 XLSTransformer 对象
            XLSTransformer xlsTransformer = new XLSTransformer();
            // 获取 Workbook ，传入 模板 和 数据
            Workbook workbook =  xlsTransformer.transformXLS(is,map);
            // 设置文件名
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(downloadName ,"UTF-8"));
            // 写出文件
            os = new BufferedOutputStream( response.getOutputStream() );
            // 输出
            workbook.write(os);
            // 关闭和刷新管道，不然可能会出现表格数据不齐，打不开之类的问题
            os.flush();
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }finally {
            try {
                if (is != null){
                    is.close();
                }
                if (os != null){
                    os.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return true;
    }


}
